package com.iflyings.android.component

import org.json.JSONObject
import java.io.PrintWriter

open class ComponentElement(name: String): ComponentContext.Element {

    final override val key = ElementKey(name)

    open val isEnabled = true

    open fun open() {}
    open fun close() {}
    open fun dump(writer: PrintWriter, suffix: String) {}
    open fun command(cmd: String, data: JSONObject): JSONObject? = null

    class ElementKey(val name: String): ComponentContext.Key<ComponentContext.Element> {

        override fun equals(other: Any?): Boolean {
            if (other == null || other !is ElementKey) {
                return false
            }
            return other.name == name
        }

        override fun hashCode(): Int {
            return name.hashCode()
        }

    }
}

fun ComponentContext.forEach(block: (ComponentElement) -> Unit) =
    fold(Unit) { _, element ->
        if (element is ComponentElement && element.isEnabled) {
            block(element)
        }
    }

fun ComponentContext.find(block: (ComponentElement) -> Boolean): ComponentElement? =
    first { it.isEnabled && block(it) }

operator fun ComponentContext.get(name: String): ComponentElement? {
    val key = ComponentElement.ElementKey(name)
    return first { return@first it.isEnabled && it.key == key }
}

inline fun <reified T: ComponentElement> ComponentContext.get(): T? {
    val clazz = T::class.java
    return first { return@first it.isEnabled && it.javaClass == clazz }
}